package com.example.tcp.server;



import com.example.MessageDecoder;
import com.example.MessageEncoder;
import com.example.codec.BootstrapConfig;
import com.example.common.constant.ConsoleColors;
import com.example.proto.Message;
import com.example.proto.MessageHeader;
import com.example.tcp.handler.HeartBeatHandler;
import com.example.tcp.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LimServer {
    private final static Logger logger= LoggerFactory.getLogger(LimServer.class);
    BootstrapConfig.TcpConfig config;
    EventLoopGroup mainGroup;
    EventLoopGroup subGroup;
    ServerBootstrap server;


    public LimServer(BootstrapConfig.TcpConfig config){
        this.config=config;
        mainGroup = new NioEventLoopGroup(config.getBossThreadSize());        //线程池
        subGroup = new NioEventLoopGroup(config.getWorkThreadSize());
        server=new ServerBootstrap();
        server.group(mainGroup,subGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG,1024)
                .option(ChannelOption.SO_REUSEADDR,true)
                .childOption(ChannelOption.TCP_NODELAY,true)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .childHandler(new ChannelInitializer<SocketChannel>(){

                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new MessageDecoder());
                        channel.pipeline().addLast(new MessageEncoder());
                        channel.pipeline().addLast(new IdleStateHandler(
                                0, 0,  //心跳检测  //第一个是读超时  第二个是写超时 第三给是读写超时
                                20));
                        channel.pipeline().addLast(new HeartBeatHandler(config.getHeartBeatTime()));  //  时间是到配置文件里面拿
                        channel.pipeline().addLast(new NettyServerHandler(config.getBrokerId(), config.getLogicUrl()));    //加了一个路径
                    }
                });

    }
    public void start(){
        this.server.bind(this.config.getTcpPort());
        logger.info(ConsoleColors.GREEN+"tcp start"+ConsoleColors.RESET);
    }

}
